package com.example.main

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.View
import android.webkit.JavascriptInterface
import androidx.appcompat.app.AlertDialog

import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.main.R
import com.bawei.main.databinding.ActivityMainBinding
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.example.base.RouterPath
import com.example.common.base.BaseActivity
import com.tencent.mmkv.MMKV
import com.tencent.smtt.sdk.WebSettings

@Route(path = RouterPath.PATH_MAIN_PAGE)
class MainActivity : BaseActivity<ActivityMainBinding>() {

    //需要的用户权限
    private var needUserPermission = arrayListOf(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA,
        Manifest.permission.READ_PHONE_STATE,
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.RECORD_AUDIO
    )

    //用户拒绝的权限
    private var unGrantPermisson = arrayListOf<String>()


    override fun getLayoutId(): Int = R.layout.activity_main

    override fun initView() {
        initX5WebView()
        loadX5WebView()
    }

    private fun initX5WebView(){
        mDataBinding.wbTencent.run {
            //初始化必要设置项
            settings.run {
                javaScriptEnabled = true //是否支持JS脚本
                allowFileAccess = true  //是否支持访问文件
                loadsImagesAutomatically= true //是否支持自动加载图片
                javaScriptCanOpenWindowsAutomatically= true //是否支持JS弹窗
                layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
                useWideViewPort = true //是否支持小窗口
                builtInZoomControls = false //是否显示放大缩小图标
                cacheMode = WebSettings.LOAD_NO_CACHE //设置缓存模式
                domStorageEnabled = true //是否支持Dom树存储

                setSupportMultipleWindows(false) //是否支持多窗口
                setSupportZoom(false) //是否支持页面缩放
                setAppCacheEnabled(true) //是否支持缓存
                setGeolocationEnabled(false) //是否支持定位功能
            }

            //设置客户端
            webChromeClient = X5WebViewChromeClient()
            webViewClient = X5WebViewClient()
        }
    }




    /**
     * SP与MMKV区别
     * 1.SP是Android系统提供一种K-V存储技术，主要存储基本数据类型，MMKV是腾讯微信团队开发的，属于第三方K-V存储技术
     * 2.SP采用的xml文件来存储数据的，读取采用IO操作，MMKV使用内存映射（mmap技术）读取操作的内存而非xml文件
     */
    private fun loadX5WebView() {
        var homeUrl = MMKV.defaultMMKV().decodeString("home_url", "")
        LogUtils.i("主页面URL：${homeUrl}")
        mDataBinding.wbTencent.loadUrl(homeUrl)
        mDataBinding.wbTencent.view.overScrollMode = View.OVER_SCROLL_NEVER

        //添加JS交互接口
        mDataBinding.wbTencent.addJavascriptInterface(WebViewJsInterface(), "androidinfo") //"androidinfo"是前端H5页面中JS调用的别名或者对象名称，比如：window.anroidinfo.方法

        //用户权限检验
        mDataBinding.wbTencent.postDelayed({
            autoRequestPermisson()
        },2000)

    }

    private fun autoRequestPermisson():Boolean {
        //SDK6.0之后需要手动发起用户授权
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){
            //清理一下历史未授权的用户权限
            unGrantPermisson.clear()
            //检查用户是否统一的用户权限
            needUserPermission.forEach{
                var state = checkSelfPermission(it)
                if(state == PackageManager.PERMISSION_DENIED){
                    unGrantPermisson.add(it)
                }

            }

            //对于用户还没有授权的用户权限发起授权弹窗
            if(unGrantPermisson.size>0){
                requestPermissions(unGrantPermisson.toTypedArray(),100)
                return false
            }

        }

        return true

    }


    /**
     * 获取用户授权的结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if(requestCode == 100 && Build.VERSION.SDK_INT>=Build.VERSION_CODES.M) {

            var hasUnGranted = false
            //是否存在还没有统一的权限
            unGrantPermisson.forEach {

                if (checkSelfPermission(it) == PackageManager.PERMISSION_DENIED) {
                    hasUnGranted = true
                }
            }
            //给出权限提示
            if (hasUnGranted) {

                var builder = AlertDialog.Builder(this@MainActivity)
                builder.setTitle("权限提示")
                builder.setMessage("没有授权,请到应用详情中设置")
                builder.setPositiveButton("去设置") { dialog, _ ->
                    dialog.dismiss()
                    hasUnGranted = false
                    //跳转到应用详情页面
                    openAppDetailPage()
                }
                builder.setNegativeButton("取消") { dialog, _ ->
                        dialog.dismiss()
                        hasUnGranted = false
                }
                //弹出提示
                builder.create().show()
            }
        }
    }
    private fun openAppDetailPage() {
        var appDetailIntent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        appDetailIntent.data = Uri.fromParts("package", packageName, null)
        this@MainActivity.startActivity(appDetailIntent)
    }



    /**
     * 跳转到对应模块
     */
    private fun jumpModuleActivity(moduleType: String) {
        //检验用户权限
        var hasAllPermission = autoRequestPermisson()
        if(!hasAllPermission){
            showToastMsg("您还没有同意相关用户权限")
            return
        }



        //根据模块ID跳转到对应页面
        when (moduleType) {
            "1", "2", "3", "4", "5", "6" -> ARouter.getInstance().build(RouterPath.PATH_PROPERTY_PAGE).withString("moduleType", moduleType).navigation()
            "7", "8", "9", "10" -> ARouter.getInstance().build(RouterPath.PATH_CULTURE_PAGE).withString("moduleType", moduleType).navigation()
            "11", "12" -> ARouter.getInstance().build(RouterPath.PATH_ATTENDANCE_PAGE).withString("moduleType", moduleType).navigation()
            "13", "14", "15" -> ARouter.getInstance().build(RouterPath.PATH_AUDIT_PAGE).withString("moduleType", moduleType).navigation()
        }
    }


    /**
     * 定义JS交互接口类
     * 特别注意：方面名必须与前端开发人员协商一致，名称保持一样
     */
    inner class WebViewJsInterface{

        @JavascriptInterface //必须添加该注解
        fun androidparking(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidapply(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidvisit(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidpatrol(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidnews(id: String) = jumpModuleActivity(id)
        @JavascriptInterface
        fun androidnoticelist(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidrepair(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidaddrepair(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidaddculture(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidaddnotice(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidculture(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidnotice(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidsign(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidattendance(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidproperty(id: String) = jumpModuleActivity(id)
        @JavascriptInterface
        fun androidcheckculture(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidpeople(id: String) = jumpModuleActivity(id)

    }

}


